from flask import Flask
from settings import Config, DevelopmentConfig
from flask_sqlalchemy import SQLAlchemy
import redis
from flask_session import Session
from flask_cors import CORS
from settings import get_log

# 记录日志
get_log(DevelopmentConfig)

app = Flask(__name__)

app.config.from_object(DevelopmentConfig)

# 在加载了配置类之后,再创建db
db = SQLAlchemy(app)

# 创建一个redis实例
# redis_store = redis.Redis(host=DevelopmentConfig.REDIS_IP, port=DevelopmentConfig.REDIS_PORT)
app.redis_store = redis.Redis(host=DevelopmentConfig.REDIS_IP, port=DevelopmentConfig.REDIS_PORT)

# 让 app 使用 Session
Session(app)

# CORS
CORS(app)

# 添加钩子函数
from flask import request
from project.utils.user import check_user_token
from flask import g


@app.before_request
def before_request():

    g.user_id = None

    # 1.request.headers 获取 token
    authorization = request.headers.get('Authorization')
    # Bearer eyJhbGciOiJIUzUxMiIsImlhdCI6MTU3Nzc3OTU0MywiZXhwIjoxNTc4Mzg0MzQzfQ.eyJ1c2VyX2lkIjoxfQ.knbtJwJGbLC8pXuF4BiK4bwEcEa4s-lVO0cSc0cdzQc2r4tiYMTaJ5N2KLcsd7q-FESVEcKzS7so-5X2muVwpw
    if authorization is not None and authorization.startswith('Bearer'):
        token = authorization[7:]
        # 2.验证token
        user_id = check_user_token(token)
        g.user_id = user_id


# 注册蓝图
from project.apps.home import home_blueprint
app.register_blueprint(home_blueprint)

from project.apps.user import user_blueprint
app.register_blueprint(user_blueprint)
